package com.bluesky.example.concurrent;

public class Producer extends Thread {

	Buffer buf;
	volatile int n;

	public Producer(Buffer buf, int n) {
		this.buf = buf;
		this.n = n;
		
		setName("producer");
	}

	@Override
	public void run() {
		while (n >= 0) {
			n--;

			
				

			double o = Math.random();

			// echo it
			System.out.println("produce:" + o);

			buf.put(o);

			try {
				sleep((int) Math.random() * 100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} // sleep for a randomly chosen
			// time

		}
		buf.setClosing(true);
		System.out.println("produce end");

	}

	public static void main(String[] args) {
		Buffer buf = new Buffer();
		int n = 10;
		Producer p = new Producer(buf, n);
		Consumer c = new Consumer(buf, n,0);
		Consumer c2 = new Consumer(buf, n,1);

		
		c.start();
		c2.start();
		p.start();
		// Wait for the threads to finish
		try {
			p.join();
			c.join();
			c2.join();
		} catch (InterruptedException e) {
			return;
		}
	}
}
